package com.svms.save.services;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.svms.save.cache.PublicCache;
import com.svms.save.entitys.SvdaRydaxx;
import com.svms.save.entitys.SvdaRydaxxExample;
import com.svms.save.entitys.SvdaYhb;
import com.svms.save.importexcel.service.ImportService;
import com.svms.save.importexcel.utils.ExcelConfig;
import com.svms.save.importexcel.vo.EntityMapping;
import com.svms.save.mapper.SvdaRydaxxCountMapper;
import com.svms.save.mapper.SvdaRydaxxMapper;
import com.svms.save.services.impl.SvdaTestToolsManager;
import com.svms.save.utils.CommonUtils;
import com.svms.save.utils.PinYinUtils;
import com.svms.save.utils.SysCode;
import com.svms.save.vo.GroupByVo;
import com.svms.save.vo.Page;
import com.svms.save.vo.ResultVo;
import com.svms.save.vo.SvdaRydaxxExtVo;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * 人员档案信息管理
 * @author xuyang
 *
 */
public abstract class SvdaRydaxxService extends BaseService{
	private Logger log = LoggerFactory.getLogger(SvdaRydaxxService.class);
	
	@Autowired
	private SvdaRydaxxMapper rydaMapper;
	@Autowired
	private SvdaZwxxxService zwxxxManager;
	@Autowired
	private SvdaYhService yhManager;
	@Autowired
	private SvdaRydaxxCountMapper rydaxxCountMapper;
	/**
	 * 数据导入服务
	 */
	@Autowired
	private ImportService importExcelManager;
	@Autowired
	private SvdaTestToolsManager svdaTestTool;
	/**
	 * 查询人员档案信息
	 * @param yhb
	 * @param page
	 * @param rydaxx
	 * @return
	 */
	public Page<SvdaRydaxx> queryRydaxx(SvdaYhb yhb,Page<SvdaRydaxx> page,SvdaRydaxx rydaxx){
		if(null != rydaxx) {
			if(StringUtils.isNotBlank(rydaxx.getXm())) {
				rydaxx.setXmjp(rydaxx.getXm().toUpperCase());
			}
            List<SvdaRydaxx> list = rydaxxCountMapper.selectRydaxxByRydaxx(rydaxx, page.getPageSize(), page.getOffset());
            long count = rydaxxCountMapper.countSelectRydaxx(rydaxx);
            page.setTotail(count);
            page.setResult(list);
		}
		return page;
	}
	
	public SvdaRydaxx findById(Long objectid) {
		return rydaMapper.selectByPrimaryKey(objectid);
	}
	
	public ResultVo<JSONArray> importsRydaxx(SvdaYhb yh,MultipartFile file) {
		ResultVo<JSONArray> res = null;
		int c = 0;
		InputStream excelIs = null;
		Workbook wb = null;
		try {
			importExcelManager.setTestTools(this.svdaTestTool);
			excelIs = file.getInputStream();
			wb = importExcelManager.getWorkbook(excelIs);
			List<EntityMapping> list = importExcelManager.getEntityMapping(wb, ExcelConfig.MAPPING_SHEET_NO);
			JSONObject json = importExcelManager.readDataByEntityMapping(wb, list);
			boolean allFlag = json.getBoolean(ExcelConfig.JSON_ALLFLAG_KEY);
			if(allFlag){
				if(null != list && !list.isEmpty()) {
					EntityMapping em = list.get(0);
					List data = em.getDataList();
					for(Object obj : data) {
						SvdaRydaxxExtVo rydaxxVo = (SvdaRydaxxExtVo) obj;
						String zwgwzbh = zwxxxManager.genZwxwzbh(rydaxxVo.getWzbh(), rydaxxVo.getZwgbh(), rydaxxVo.getCsbh(), rydaxxVo.getCgsbh());
						rydaxxVo.setSsdag(zwgwzbh);
						String daxxbh = CommonUtils.getUUID();
						rydaxxVo.setDaxxbh(daxxbh);
						String ssjg = rydaxxVo.getSsjg();
						String daryzt = rydaxxVo.getDaryzt();
						String ssjgdm = PublicCache.getZddmByZdmc(SysCode.JGBM_ZD, ssjg);
						String daryztdm = PublicCache.getZddmByZdmc(SysCode.RYZT_ZD, daryzt);
						rydaxxVo.setSsjg(ssjgdm);
						rydaxxVo.setDaryzt(daryztdm);
						int r = this.doSave(yh, rydaxxVo);
						c += r;
					}
					String msg = String.format("导入完成，共计导入%s条数据！", c);
					res = ResultVo.success(msg, null);
				}
			}else {
				res = ResultVo.businessError(json.getString(ExcelConfig.JSON_MSG_KEY), json.getJSONArray(ExcelConfig.JSON_ITEMS_KEY));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.error("系统错误！",e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("系统错误！",e);
		}finally{
			if(null != excelIs){
				try {
					excelIs.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					log.error("系统错误！",e);
				}
			}
			if(null != wb){
				wb.close();
			}
		}
		return res;
	}
	public long countAllRyda() {
		SvdaRydaxxExample ex = new SvdaRydaxxExample();
		SvdaRydaxxExample.Criteria cri = ex.createCriteria();
		cri.andCzbsNotEqualTo("3");
		long conut = rydaMapper.countByExample(ex);
		return conut;
	}
	
	public List<GroupByVo> groupByDaryzt(){
		SvdaRydaxxExample ex = new SvdaRydaxxExample();
		SvdaRydaxxExample.Criteria cri = ex.createCriteria();
		cri.andCzbsNotEqualTo("3");
		List<GroupByVo> list = rydaxxCountMapper.selectGroupByDaryzt(ex);
		return list;
	}
	public List<GroupByVo> groupBySsjg(){
		SvdaRydaxxExample ex = new SvdaRydaxxExample();
		SvdaRydaxxExample.Criteria cri = ex.createCriteria();
		cri.andCzbsNotEqualTo("3");
		List<GroupByVo> list = rydaxxCountMapper.selectGroupBySsjg(ex);
		return list;
	}
	public List<GroupByVo> groupByLeftSsjg(){
		SvdaRydaxxExample ex = new SvdaRydaxxExample();
		SvdaRydaxxExample.Criteria cri = ex.createCriteria();
		cri.andCzbsNotEqualTo("3");
		List<GroupByVo> list = rydaxxCountMapper.selectGroupByLeftSsjg(ex);
		return list;
	}
	
	public int doSave(SvdaYhb yh,SvdaRydaxx rydaxx) {
		int r = 0;
		super.setEntityDefVal(yh, rydaxx);
		rydaxx.setXmjp(PinYinUtils.getPinYinHeadChar(rydaxx.getXm()));
		if(null == rydaxx.getObjectid()) {
			rydaxx.setDaxxbh(CommonUtils.getUUID());
			rydaxx.setDqzt(SysCode.DAZT_ZC);
			r = rydaMapper.insert(rydaxx);
			rydaxx.setCzbs(SysCode.CZBS_ADD);
		}else {
			r = rydaMapper.updateByPrimaryKey(rydaxx);
			rydaxx.setCzbs(SysCode.CZBS_UPDATE);
		}
		return r;
	}
	/**
	 * 翻译姓名简拼
	 * @param yh
	 * @return
	 */
	public int updateXmjp(SvdaYhb yh) {
		int c = 0;
		SvdaRydaxxExample ex = new SvdaRydaxxExample();
		SvdaRydaxxExample.Criteria cri = ex.createCriteria();
		cri.andXmjpIsNull();
		cri.andCzbsNotEqualTo("3");
		List<SvdaRydaxx> list = rydaMapper.selectByExample(ex);
		if(null != list && list.size() > 0) {
			for(SvdaRydaxx item : list) {
				c+=this.doSave(yh, item);
			}
		}
		return c;
	}
	
	public void exportExcel(SvdaYhb yhb,SvdaRydaxx rydaxx,OutputStream os) {
		List<SvdaRydaxx> list = rydaxxCountMapper.selectRydaxxByRydaxx(rydaxx, SysCode.EXPORT_MAX, 0);
		WritableWorkbook wwb = null;
		try {
			wwb = Workbook.createWorkbook(os);
			WritableSheet sheet = wwb.createSheet("导出结果", 0);
			Label xhTitle = new Label(0,0,"序号");
			Label xmTitle = new Label(1,0,"姓名");
			Label ssdwTitle = new Label(2,0,"所属单位");
			Label ryztTitle = new Label(3,0,"人员状态");
			sheet.addCell(xhTitle);
			sheet.addCell(xmTitle);
			sheet.addCell(ssdwTitle);
			sheet.addCell(ryztTitle);
			if(null != list && !list.isEmpty()) {
				for(int i=0;i<list.size();i++) {
					SvdaRydaxx ryda = list.get(i);
					int r = i +1;
					sheet.addCell(new Label(0,r,r+""));
					sheet.addCell(new Label(1,r,ryda.getXm()));
					String ssdwMc = PublicCache.getZdmcByLxjpZddm(SysCode.JGBM_ZD, ryda.getSsjg(), false);
					sheet.addCell(new Label(2,r,ssdwMc));
					String ryztMc = PublicCache.getZdmcByLxjpZddm(SysCode.RYZT_ZD, ryda.getDaryzt(), false);
					sheet.addCell(new Label(3,r,ryztMc));
				}
			}
			wwb.write();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("导出时系统发生错误！",e);
		}finally {
			try {
				if(null != wwb) {
					wwb.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("系统发生错误！",e);
			}
		}
		
	}
	
	public int delRydaxxByObjectid(SvdaYhb yh,SvdaRydaxx rydaxx) {
		rydaxx.setCzbs(SysCode.CZBS_DELETE);
		super.setEntityDefVal(yh, rydaxx);
		int r = rydaMapper.updateByPrimaryKeySelective(rydaxx);
		return r;
	}
}